<template>
    <div>
        <div class="header">
            <el-form :inline="true" ref="form" label-width="80px">
                <el-form-item>
                    <el-input placeholder="用户名" v-model="username"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="getLimitUserList">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button @click="clear">清空</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div style="margin-bottom: 20px;">
            <el-button type="primary" @click="addUser">添加</el-button>
            <el-button type="danger" :disabled="selectedIds.length === 0" @click="removeUsers">批量删除</el-button>
        </div>

        <el-table ref="multipleTable" :data="userData" tooltip-effect="dark" style="width: 100%"
            @selection-change="handleSelectionChange" border v-loading="listLoading">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column label="序号" width="80" align="center" type="index"></el-table-column>
            <el-table-column prop="username" label="用户名" width="120"></el-table-column>
            <el-table-column prop="nickName" label="用户昵称" width="80"></el-table-column>
            <el-table-column prop="roleName" label="权限列表" width="80"></el-table-column>
            <el-table-column prop="gmtCreate" label="创建时间"> </el-table-column>
            <el-table-column prop="gmtModified" label="更新时间"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="{$index, row}">
                    <el-button type="info" size="mini" icon="el-icon-user-solid" @click="getUserRole(row)"></el-button>
                    <el-button type="primary" size="mini" icon="el-icon-edit" @click="edit(row)"></el-button>
                    <el-popconfirm :title="`确定删除${row.username}吗？`" @onConfirm="deleteUser(row.id)">
                        <el-button slot="reference" icon="el-icon-delete" type="danger" size="mini"
                            style="margin-left: 10px;"></el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination :current-page="page" :page-sizes="[3, 5, 10]" :page-size="limit"
            layout="prev, pager, next, jumper, ->,sizes, total" :total="total" style="margin-top: 15px;"
            @size-change="handleSizeChange" @current-change="handleCurrentChange">
        </el-pagination>

        <el-dialog title="添加用户" :visible.sync="UserFormVisible">
            <el-form :model="userObj" label-width="120px" :rules="userRules" ref="userForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userObj.username"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称">
                    <el-input v-model="userObj.nickName"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password" v-show="!userObj.id">
                    <el-input v-model="userObj.password"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="UserFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveUser" :loading="loading">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="设置角色" :visible.sync="roleFormVisible">
            <el-form label-width="80px">
                <el-form-item label="活动名称">
                    <el-input v-model="userObj.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="角色列表">
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
                        @change="handleCheckAllChange">全选</el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRoleChange">
                        <el-checkbox v-for="role in allRolesList" :label="role.id" :key="role.id">{{ role.roleName
                            }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="roleFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveUserRole" :loading="loading">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
export default {
    name: 'User',
    data() {
        return {
            username: '',
            userData: [],
            page: 1,
            limit: 3,
            total: 30,
            UserFormVisible: false,
            roleFormVisible: false,
            userObj: {},
            userRules: {
                username: [
                    { required: true, message: '用户名必须输入' },
                    { min: 4, message: '用户名不能小于4位' }
                ],
                password: [
                    { required: true, message: '密码必须输入' },
                    { min: 6, message: '密码不能小于6位' }
                ]
            },
            // 所有存在的角色
            allRolesList: [],
            // 某个用户选择的角色的id的集合
            // 选中的角色
            checkedRoles: [],
            checkAll: false,
            isIndeterminate: false,
            selectedIds: [],
            // 列表显示加载提示标志
            listLoading: false,
            loading: false
        }
    },
    mounted() {
        this.getUserList()
    },
    methods: {
        // 选择用户
        handleSelectionChange(selected) {
            this.selectedIds = selected.map(item => item.id)
        },
        handleSizeChange(limit) {
            this.limit = limit
            this.getUserList()
        },
        handleCurrentChange(page) {
            this.page = page
            this.getUserList()
        },
        // 清空搜索关键字
        clear() {
            this.username = ''
            this.page = 1
            this.getUserList()
        },
        async getUserList() {
            this.listLoading = true
            let result = await this.$API.user.reqUserList(this.page, this.limit, this.username)
            if (result.code == 20000) {
                this.userData = result.data.items
                this.total = result.data.total
                this.listLoading = false
            }
        },
        // 获取查询的用户名
        getLimitUserList() {
            this.page = 1
            this.getUserList()
        },
        // 添加按钮
        addUser() {
            this.userObj = {}
            this.UserFormVisible = true
            // 清空校验
            this.$nextTick(() => this.$refs.userForm.clearValidate())
        },
        // 保存或更新用户
        saveUser() {
            // 只有校验成功才能保存
            this.$refs.userForm.validate(async valid => {
                if (valid) {
                    this.loading = true
                    this.UserFormVisible = false
                    let result = 0
                    if (this.userObj.id) {
                        result = await this.$API.user.reqUpdateUser(this.userObj)
                    } else {
                        result = await this.$API.user.reqSaveUser(this.userObj)
                    }

                    if (result.code == 20000) {
                        this.$message({ type: 'success', message: '保存成功' })
                        this.getLimitUserList()
                        this.loading = false
                    }
                }
            })
        },
        // 编辑用户
        edit(user) {
            this.userObj = cloneDeep(user)
            this.UserFormVisible = true
        },
        // 删除用户
        async deleteUser(id) {
            let result = await this.$API.user.reqDeleteUser(id)
            if (result.code == 20000) {
                if (this.userData.length <= 1) {
                    this.page = 1
                } else {
                    this.page -= 1
                }
                this.$message({ type: 'success', message: '删除成功' })
                this.getUserList()
            } else {
                this.$message({ type: 'info', message: '删除失败' })
            }
        },
        // 获取用户的角色
        async getUserRole(user) {
            let result = await this.$API.user.reqUserRole(user.id)

            if (result.code == 20000) {
                const { allRolesList, assignRoles } = result.data
                this.allRolesList = allRolesList
                this.checkedRoles = assignRoles.map(item => item.id)
                this.checkAll = assignRoles.length === allRolesList.length
                this.isIndeterminate = assignRoles.length > 0 && assignRoles.length < allRolesList.length
                this.userObj = user
                this.roleFormVisible = true

            }
        },
        handleCheckedRoleChange(checkedRoles) {
            this.checkedRoles = checkedRoles
            this.checkAll = this.checkedRoles.length === this.allRolesList.length
            this.isIndeterminate = this.checkedRoles.length > 0 && this.checkedRoles.length < this.allRolesList.length
        },
        handleCheckAllChange(checked) {
            this.checkAll = checked
            this.isIndeterminate = this.checkedRoles.length > 0 && this.checkedRoles.length < this.allRolesList.length
            this.checkedRoles = checked ? this.checkedRoles = this.allRolesList.map(item => item.id) : this.checkedRoles = []
        },

        // 保存所选用户的角色
        async saveUserRole() {
            this.loading = true
            let result = await this.$API.user.reqSaveUserRoles(this.userObj.id, this.checkedRoles)
            if (result.code == 20000) {
                this.roleFormVisible = false
                this.$message({ type: 'success', message: '保存成功' })
                this.loading = false
            }
        },
        // 批量删除
        removeUsers() {
            this.$confirm("确定删除?", {
                confirmButtonText: '确认',
                cancelButtonText: '取消'
            }).then(async () => {
                try {
                    await this.deleteAll()
                    this.$message({ type: 'success', message: '全部删除成功' })
                    this.getUserList()
                } catch {
                    this.$message({ type: 'info', message: '全部删除出现删除失败' })
                }
            }).catch((error) => {
                this.$message({ type: 'info', message: '取消删除' })
            })
        },

        // 删除
        deleteAll() {
            let PromiseAll = []
            this.selectedIds.forEach(async (item) => {
                let res = await this.$API.user.reqDeleteUser(item)
                if (res.code === 20000) {
                    PromiseAll.push("ok")
                } else {
                    PromiseAll.push(Promise.reject(new Error('faile')))
                }
            });

            return Promise.all(PromiseAll)
        }
    }
}
</script>

<style></style>